﻿using Chromium;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;

namespace M5.GeminiHybird.Core.XHR.Controller
{
    public class BaseController
    {


        public string ActionName { get; set; }

        public string Execute(string routeData)
        {

            Dictionary<string, string> dataPairs = null;
            try
            {
                //axios传入的数据是json
                dataPairs = JsonConvert.DeserializeObject<Dictionary<string, string>>(routeData);
            }
            catch
            {

            }

            if (!string.IsNullOrEmpty(routeData) && dataPairs == null)
            {
                foreach (var item in routeData.Split('&'))
                {
                    if (item.IndexOf("=") <= 0)
                    {
                        throw new ArgumentException("请求传递的参数必须是键值对");
                    }
                    var arr = item.Split('=');
                    dataPairs.Add(arr[0].ToLower(), arr[1]);
                }
            }


            Type t = this.GetType();
            BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase;
            MethodInfo methodInfo = t.GetMethod(ActionName, flag);

            ParameterInfo[] paramsInfo = methodInfo.GetParameters();

            object[] paramsArray = new object[paramsInfo.Length];
            for (int i = 0; i < paramsInfo.Length; i++)
            {
                Type parameterType = paramsInfo[i].ParameterType;
                string name = paramsInfo[i].Name.ToLower();
                try
                {
                    paramsArray[i] = Convert.ChangeType(dataPairs[name], parameterType);
                }
                catch (Exception)
                {
                }

            }

            var result = methodInfo.Invoke(this, paramsArray);

            if (typeof(string) == result.GetType())
            {
                return result.ToString();
            }

            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            string jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(result, settings);
            return jsonStr;
        }

    }
}
